package org.example.wu_and_dian.utils;

import io.jsonwebtoken.*;
import io.jsonwebtoken.security.Keys;

import javax.crypto.SecretKey;
import java.util.Date;

public class TokenUtils {
    private static SecretKey secretKey= Keys.hmacShaKeyFor("Io2DnxSKyixV@3DI6DLS9yfS&i%D%2gM".getBytes());
    //生成token
    public static String createToken(String email,String password){
        return Jwts.builder()
                .setExpiration(new Date(System.currentTimeMillis() + 3600000*24*365L))
                .setSubject("LOGIN_USER")
                .claim("email", email)
                .claim("password", password)
                .signWith(secretKey, SignatureAlgorithm.HS256).compact();
    }
    //解析token
    public static Claims parseToken(String token){
        //验证token是否为空，如果为空，说明未登录
        if(token==null){
            throw new RuntimeException("未登录");
        }
        try {
            JwtParser jwtParser = Jwts.parserBuilder().setSigningKey(secretKey).build();
            Jws<Claims> claimsJws = jwtParser.parseClaimsJws(token);
            return claimsJws.getBody();
        }catch (ExpiredJwtException e){
            throw new RuntimeException("token已过期");
        }catch (JwtException e){
            throw new RuntimeException("token无用");
        }
    }


}
